package org.paic.vertx.httpwrapper.render;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;

import org.lilystudio.smarty4j.Context;
import org.lilystudio.smarty4j.Engine;
import org.lilystudio.smarty4j.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Smarty4jRender implements Render {
	private final static String CONF = "/config/smarty4j.properties";
	private final static String DEFAUL_ENCODING = "utf-8";

	private Engine engine = new Engine();

	private Logger log = LoggerFactory.getLogger(Smarty4jRender.class);

	private void setting() throws IOException {
		engine.setEncoding(DEFAUL_ENCODING);

		InputStream is = Smarty4jRender.class.getClassLoader()
				.getResourceAsStream(CONF);
		if (is == null)
			return;

		Properties props = new Properties();
		props.load(is);

		engine.setDebug("true".equals(props.getProperty("isDebug")));
		String encoding = props.getProperty("encoding");
		if (encoding != null)
			engine.setEncoding(encoding);

		String templatePath = props.getProperty("templatePath");
		if (templatePath != null)
			engine.setTemplatePath(templatePath);
	}

	public Smarty4jRender() {
		try {
			setting();
		} catch (IOException e) {
			log.error("Create Smarty4jRender instance failed!", e);
		}
	}

	@Override
	public void render(String tpl, Map<String, Object> model, OutputStream out)
			throws Exception {
		Template template = engine.getTemplate(tpl);
		Context context = new Context();
		context.putAll(model);
		template.merge(context, out);
	}

	@Override
	public String render(String tpl, Map<String, Object> model)
			throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		render(tpl, model, out);

		return new String(out.toByteArray(), engine.getEncoding());
	}
}
